import React, { Component } from 'react';
import { connect } from 'dva';
import sha1 from 'sha1';
import { Form, Icon, Input, Button, Row, Col, Card, Select } from 'antd';
import style from './ModifyPwd.less';

const { Option } = Select;
function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

class ModifyPwd extends Component {
  state = {
    confirmDirty: false,
    strength: -1, // 密码强度
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        this.props.dispatch({
          type: 'modifyPwd/setPwd',
          payload: {
            original_password: sha1(values.original_password),
            new_password: sha1(values.new_password),
          },
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value.length < 6) {
      callback('密码长度不能小于6位！');
    } else if (value && sha1(value) !== sha1(form.getFieldValue('new_password'))) {
      callback('两次输入密码不一致!');
    } else {
      callback();
    }
  };

  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    this.checkStrong(value);
    if (value && value.length < 6) {
      callback('密码长度不能小于6位！');
    } else if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };

  checkStrong = val => {
    let modes = 0;
    if (val.length === 0) return -1;
    if (val.length < 6) return 0;
    if (/\d/.test(val)) modes++; //数字
    if (/[a-z]/.test(val)) modes++; //小写
    if (/[A-Z]/.test(val)) modes++; //大写
    if (/\W/.test(val)) modes++; //特殊字符
    if (val.length > 12) modes++;
    this.setState({
      strength: Math.round((modes * 3) / 5), // 1.2 > 1, 1.6 > 2
    });
  };

  render() {
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    const { strength } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <Card style={{ border: 'none' }}>
        <Row>
          <Form onSubmit={this.handleSubmit}>
            <Form.Item {...formItemLayout} label="原密码：">
              {getFieldDecorator('original_password', {
                rules: [{ required: true, message: '请输入原密码!' }],
              })(<Input type="password" placeholder="" />)}
            </Form.Item>

            <Form.Item {...formItemLayout} label="新密码：">
              {getFieldDecorator('new_password', {
                rules: [
                  { required: true, message: '请输入新密码!' },
                  { validator: this.checkConfirm },
                ],
              })(<Input type="password" placeholder="" />)}
            </Form.Item>
            <Row>
              <Col offset={4} span={20} style={{ fontSize: '13px' }}>
                密码区分大小写，不包含空格，长度不能大与20个字符
              </Col>
            </Row>
            <Form.Item {...formItemLayout} label="密码强度">
              <div className={style.wrapper}>
                <div
                  id="div1"
                  className={style.strength + ' ' + (strength >= 1 ? style.rank1 : '')}
                />
                <div
                  id="div2"
                  className={style.strength + ' ' + (strength >= 2 ? style.rank2 : '')}
                />
                <div
                  id="div3"
                  className={
                    style.strength + ' ' + style.last + ' ' + (strength >= 3 ? style.rank3 : '')
                  }
                />
              </div>
            </Form.Item>

            <Form.Item {...formItemLayout} label="确认密码：">
              {getFieldDecorator('confirm', {
                rules: [
                  { required: true, message: '请输入确认密码!' },
                  { validator: this.checkPassword },
                ],
              })(<Input type="password" placeholder="" onBlur={this.handleConfirmBlur} />)}
            </Form.Item>

            <Form.Item {...tailFormItemLayout}>
              <Button style={{ marginRight: '8px' }} type="primary" htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Form>
        </Row>
      </Card>
    );
  }
}

export default connect()(Form.create({ name: 'ModifyPwd' })(ModifyPwd));
